<template>
  <div class="app-container">
    <div class="filter-container">
      <k-input
        v-model.trim="listQuery.name"
        class="filter-item"
        is-search
        placeholder="请输入关键词"
        :search-fun="handleFilter"
        @keyup.enter.native="handleFilter"
      />
    </div>
    <!-- openAssignAccountDialog -->
    <k-button
      v-if="authorityHandle(376)"
      class="top-btn"
      value="创建公司"
      @click.native="addBoxDialog"
    />
    <k-button
      v-if="authorityHandle(376)"
      class="top-btn"
      value="删除公司"
      @click.native="deleteBox"
    />
    <k-button
      v-if="authorityHandle(376)"
      class="top-right-btn"
      value="手续费配置"
      @click.native="HandlingCharge"
    />
    <!--表格相关 -->
    <el-table
      :data="boxList"
      fit
      border
      highlight-current-row
      style="width: 100%; border-radius: 8px; margin-top: 20px"
      :header-cell-style="{ background: '#F6F5FA', color: '#4E4F62' }"
      @selection-change="handleSelectionChange"
      @sort-change="sortChange"
    >
      <el-table-column
        v-if="authorityHandle(376)"
        min-width="60px"
        type="selection"
        align="center"
      />
      <el-table-column width="60px" label="序号" type="index" align="center" />
      <el-table-column
        prop="name"
        min-width="120px"
        label="公司名称"
        align="center"
      />
      <el-table-column
        prop="createTime"
        min-width="120px"
        label="创建时间"
        show-overflow-tooltip
        align="center"
      />

      <el-table-column min-width="300px" label="操作" align="center">
        <template slot-scope="scope">
          <div class="op-div">
            <template>
              <el-switch
                v-model="scope.row.enabled"
                active-color="#3b425d"
                inactive-color="#E9EBF2"
                active-text="启用"
                inactive-text="关闭"
                :active-value="1"
                :inactive-value="0"
                :disabled="!authorityHandle(376)"
                @change="boxOnlineState(scope.row)"
              />
            </template>
            <k-button
              v-if="authorityHandle(376)"
              class="table-btn"
              value="查看/修改"
              @click.native="addBoxDialog(scope.row)"
            />
            <k-button
              v-if="authorityHandle(376)"
              class="table-btn"
              value="配置主播"
              @click.native="addItemDialog(scope.row)"
            />
            <k-button
              v-if="authorityHandle(376)"
              class="table-btn"
              :disabled="scope.row.isDefault == 1"
              value="设置默认"
              @click.native="defaultDialog(scope.row)"
            />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="totalRows > 0"
      :total="totalRows"
      :page.sync="listQuery.pager.pageNo"
      :limit.sync="listQuery.pager.pageSize"
      @pagination="loadData"
    />
    <!-- 添加卡包 addBox 弹窗 -->
    <k-dialog
      :show-hide.sync="addBox.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      class="addBox-dialog"
      title="创建/修改"
      :show-foot="false"
      :two-btn="true"
      :close-fun="handleCloseDialog"
      @click="saveBoxData"
    >
      <el-form :model="addBoxInfo" label-width="auto" class="form-modify">
        <el-form-item label="公司名称：" prop="name">
          <el-input
            v-model="addBoxInfo.boxName"
            maxlength="20"
            show-word-limit
            placeholder="请输入公司名称"
          />
        </el-form-item>
      </el-form>
    </k-dialog>

    <!-- 弹药配置 弹窗 -->
    <k-dialog
      :show-hide.sync="addBox.bulletSetting"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="手续费配置"
      class-name="creatRollRoom_dialog"
      :show-foot="false"
      :two-btn="authorityHandle(376)"
      @click="saveBulletSetting"
    >
      <div class="set_box">
        <div class="Recharge_Data">
          <div class="Recharge_Data_box">
            <span>概率:</span>
            <el-input
              v-model="bulletSettingItemListPro"
              @input="formatNum(bulletSettingItemListPro)"
            />
            %
          </div>
        </div>
      </div>
    </k-dialog>
    <!-- 配置主播 弹窗 -->
    <k-dialog
      :show-hide.sync="addBaby"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="配置主播"
      class-name="creatRollRoom_dialog"
      :show-foot="false"
      :two-btn="authorityHandle(376)"
      @click="saveWelfareData"
    >
      <div class="welfare_box">
        <el-form label-width="120px">
          <el-form-item label="所属公司：">
            <el-input
              v-model="welfareData.name"
              style="width: 400px !important"
              disabled
            />
          </el-form-item>
          <el-form-item label="所属主播：">
            <el-select
              v-model="welfareData.activityId"
              value-key="anchorName"
              multiple
              remote
              clearable
              reserve-keyword
              style="width: 400px !important"
              filterable
              placeholder="请选择"
              :disabled="!authorityHandle(376)"
            >
              <el-option
                v-for="(item, index) in boxsResultList"
                :key="item.id"
                :label="item.anchorName"
                :value="item"
                @click.native="changeActivityId(item)"
              />
            </el-select>
          </el-form-item>
          <div class="tag_tent">
            <el-tag
              v-for="tag in data_wel"
              :key="tag.id"
              closable
              class="tag"
              @close="handleClose(tag)"
            >
              {{ tag.anchorName }}
            </el-tag>
          </div>
        </el-form>
      </div>
    </k-dialog>
  </div>
</template>

<script>
import { getBoxStageList } from "@/api/rules/listdata";
import {
  getAnchorPremium,
  setAnchorPremium,
  anchorDefault,
  changeCompanyEnabled,
  anchorSaveCompany,
  chooseAnchor,
  getAllCompany,
  anchorDeleteCompany,
  getCanChooseAnchor,
  getSelectedAnchor,
} from "@/api/company/index";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

export default {
  components: { Pagination },
  dicts: ["BOX_UPDOWN_STATUS"],
  data() {
    return {
      currentBoxId: undefined,
      bulletSettingItemListPro: undefined,
      divideZone: {
        divideZoneArray: [
          {
            id: undefined,
            boxId: -1,
            minPercent: "",
            maxPercent: "",
            openSort: 0,
          },
        ],
      },
      addBaby: false,
      multipleSelection: [],
      addBoxInfo: {
        id: "", // 保存卡包配置时必传",
        imgUrl: "", // 卡包图标",
        goodsImgUrl: "", // 赠品展示缩略图",
        boxName: "", // 公司名称",
        openAnimationUrl: "",
        stopUrl: "",
      },
      boxList: [],
      totalRows: 0, // 分页组件--数据总条数
      listQuery: {
        pager: {
          pageNo: 1,
          pageSize: 10,
          totalRows: "",
          start: "",
        },
        boxStatus: undefined, // 上架1  下架2,
        startTime: undefined, // 赠品外观',
        endTime: undefined, // 赠品类别',
        key: "", // 卡包名称或关键词 卡包配置界面所用'
      },
      timeValue: "",
      addBox: {
        showHide: false,
        bulletSetting: false,
      },
      addBoxUpdate: {
        showHide: false,
      },
      quickDiscountShow: false,
      boxDiscount: {
        discountValue: 0,
        startTime: undefined,
        endTime: undefined,
      },
      discountTime: "",
      bulletSetting: false,
      smartDivideZoneDialog: false,
      smartWarningDialog: false,
      dialogStatus: "create",
      textMap: {
        update: "修改公司",
        create: "创建公司",
      },

      /* 活动福利配置*/
      welfareSetting: false, // 弹框
      resultList: [], // 全部赠品

      boxsResultList: [],
      welfareProbability: undefined,
      welfareData: {
        boxCardSettings: [],
        boxId: undefined,
        activityId: [],
        name: "",
      },
      boxCardSettings: [
        {
          probability: undefined,
          goodsId: undefined,
          customPrice: undefined,
        },
      ],
      expected_value: 0,
      // 添加限制
      addItemInfo: {
        id: "",
        openNum: 0,
        astrictStatus: 2,
      },
      addBoxShowHide: false,
      data_wel: [],
    };
  },
  watch: {
    // 时间赋值
    timeValue(val) {
      this.listQuery.startTime = this.timeValue ? this.timeValue[0] : null;
      this.listQuery.endTime = this.timeValue ? this.timeValue[1] : null;
    },
  },
  created() {
    this.loadData();
    this.getSmartDivideZone();
  },

  methods: {
    // 设置默认
    defaultDialog(v) {
      this.$confirm("此操作将该公司设置为默认公司, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          anchorDefault({ id: v.id }).then((res) => {
            if (res.data.success) {
              this.$message.success("操作成功");
              this.loadData();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
    },
    querySearchAsync(queryString, cb) {
      var restaurants = this.boxsResultList;
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;

      cb(results);
    },
    formatNum(val, key) {
      let temp = val.toString();
      temp = temp.replace(/。/g, ".");
      temp = temp.replace(/[^\d.]/g, ""); // 清除"数字"和"."以外的字符
      temp = temp.replace(/^\./g, ""); // 验证第一个字符是数字
      temp = temp.replace(/\.{2,}/g, ""); // 只保留第一个, 清除多余的
      temp = temp.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      temp = temp.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); // 只能输入两个小数
      this.bulletSettingItemListPro = temp;
    },

    // 获取手续费
    HandlingCharge() {
      getAnchorPremium().then((res) => {
        this.bulletSettingItemListPro = res.data;
        this.addBox.bulletSetting = true;
      });
    },
    // 保存手续费
    saveBulletSetting() {
      console.log(this.bulletSettingItemListPro);
      if (!this.bulletSettingItemListPro)
        return this.$message.error("不可为空");
      setAnchorPremium({ data: this.bulletSettingItemListPro }).then((res) => {
        console.log(res.data);
        this.bulletSettingItemListPro = res.data;
        this.addBox.bulletSetting = false;
      });
    },
    addBoxDialog(v) {
      if (!v) this.addBoxInfo.boxName = "";
      else {
        this.addBoxInfo.id = v.id;
        this.addBoxInfo.boxName = v.name;
      }
      console.log(v.name, this.addBoxInfo.boxName);
      // this.$resetForm(this.addBoxInfo)
      this.addBox.showHide = true;
    },
    // 添加卡包
    saveBoxData() {
      if (this.addBoxInfo.boxName == undefined)
        return this.$message.error("公司名称不可为空");
      console.log(this.addBoxInfo.boxName);
      if (this.addBoxInfo.id) {
        anchorSaveCompany({
          id: this.addBoxInfo.id,
          name: this.addBoxInfo.boxName,
        }).then((res) => {
          if (!res.data.success) this.$message.error(res.data.msg);
          else {
            this.addBox.showHide = false;
            this.loadData();
            this.$message.success("保存成功");
          }
        });
      } else {
        anchorSaveCompany({ name: this.addBoxInfo.boxName }).then((res) => {
          if (!res.data.success) this.$message.error(res.data.msg);
          else {
            this.addBox.showHide = false;
            this.loadData();
            this.$message.success("保存成功");
          }
        });
      }
    },
    // 配置主播
    saveWelfareData(v) {
      const idss = [];
      this.data_wel.map((res, index) => {
        idss.push(res.id);
      });
      chooseAnchor({ id: this.addItemInfo.id, ids: idss }).then((res) => {
        if (!res.data.success) this.$message.error(res.data.msg);
        else {
          this.addBaby = false;
          this.$message.success(res.data.msg);
          this.data_wel = [];
        }
      });
    },
    // 所选主播标签删除
    handleClose(tag) {
      this.welfareData.activityId.splice(
        this.welfareData.activityId.indexOf(tag),
        1
      );
    },
    // 改状态
    boxOnlineState(v) {
      changeCompanyEnabled({ id: v.id }).then((res) => {
        console.log(res);
        if (res.data.success) this.$message.success(res.data.msg);
        else this.$message.error(res.data.msg);
      });
    },
    change(e, item) {
      const data = this.resultList.find((value) => value.lineId == e);
      item.customPrice = data.price;
    },

    // 单个删除
    curItem(index) {
      this.boxCardSettings.splice(index, 1);
    },

    addItem() {
      this.boxCardSettings.push({
        probability: undefined,
        goodsId: undefined,
        customPrice: undefined,
      });
    },
    getSmartDivideZone() {
      getBoxStageList({ id: -1 }).then((res) => {
        this.divideZone.divideZoneArray = res.data;
      });
    },
    loadData() {
      getAllCompany(this.listQuery).then((res) => {
        console.log(res);
        this.boxList = res.data;
      });
    },
    // 选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 表格的排序条件发生变化的时候会触发该事件
    sortChange(column, prop, order) {
      this.listQuery.sort = column.prop;
      if (column.order === "ascending") {
        this.listQuery.direction = "asc";
      } else if (column.order === "descending") {
        this.listQuery.direction = "desc";
      }
      this.loadData();
    },
    // 搜索查询事件
    handleFilter() {
      this.loadData();
    },
    // 删除卡包
    deleteBox() {
      const _vue = this;
      if (_vue.multipleSelection.length < 1) {
        this.$message.error("请至少选择一条数据进行删除！");
        return;
      }
      const selections = _vue.multipleSelection;

      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const ids = [];
          for (let i = 0; i < selections.length; i++) {
            ids.push(selections[i].id);
          }
          anchorDeleteCompany({ ids: ids }).then((res) => {
            if (res.data.success) {
              this.$message.success("删除成功");
              this.loadData();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    addBoxUpdateDialog(row) {
      this.addBoxUpdate.showHide = true;
      this.addBoxInfo.id = row.id;
      this.addBoxInfo.boxName = row.boxName;
      this.addBoxInfo.imgUrl = row.imgUrl;
      this.addBoxInfo.goodsImgUrl = row.goodsImgUrl;
      this.addBoxInfo.openAnimationUrl = row.openAnimationUrl;
      this.addBoxInfo.stopUrl = row.stopUrl;
      // this.$log(this.addBoxInfo)
    },
    successUpload(data, flag) {
      if (flag === 0) {
        this.addBoxInfo.imgUrl = data;
      } else if (flag === 1) {
        this.addBoxInfo.goodsImgUrl = data;
      } else if (flag === 2) {
        this.addBoxInfo.openAnimationUrl = data;
      } else if (flag === 3) {
        this.addBoxInfo.stopUrl = data;
      }
    },
    changeActivityId(item) {
      this.data_wel.push(item);
      console.log(this.data_wel);
    },
    handleCloseDialog() {
      this.$resetForm(this.addBoxInfo);
      this.addBox.showHide = false;
    },
    // 添加卡包限制
    addItemDialog(row) {
      this.welfareData.name = row.name;
      getCanChooseAnchor({ id: row.id }).then((res) => {
        console.log(res, "222222222222");
        this.boxsResultList = res.data;
      });
      getSelectedAnchor({ id: row.id }).then((res) => {
        this.data_wel = res.data;
        this.welfareData.activityId = res.data;
        console.log(this.welfareData.activityId);
      });
      this.addBaby = true;
      this.addItemInfo = { ...row };
    },
  },
};
</script>
<style lang="scss" scoped>
$menuText: #14162e; // 侧边栏字体颜色
$hoverColor: #1d143c; // 鼠标停留主色调浅色
$mainColor: #3b425d; // 主色调

.top-right-btn {
  position: absolute;
  right: 20px;
  top: 100px;
  background-color: #3b425d;
  border-color: transparent;
  color: #fff;

  &:hover {
    color: #fff;
    background-color: $hoverColor;
  }

  &:active {
    background-color: #070a29;
    color: #fff;
  }
}

.warning_div {
  .second {
    line-height: 40px;
    margin-left: 10px;
  }
}

.dialog-warningSetting {
  ::v-deep.el-input {
    width: 110px;
  }

  .price-input {
    width: 150px;
  }

  .el-icon {
    &-circle-plus,
    &-remove {
      font-size: 22px;
      color: #3b425d;
      margin-left: 10px;
    }
  }
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;

  li {
    margin: 0 0 30px 0px;
    display: flex;
    flex-direction: row;
    align-items: center;

    .warning-title {
      font-size: 16px;
      color: #14162e;
      margin-right: 30px;
    }

    i {
      color: #d1d5dd;
    }
  }
}

.filter-container {
  width: 100%;
  height: 48px;
  line-height: 48px;

  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 30px;
  }

  .kInput {
    position: absolute;
    right: 20px;
  }

  .filter-title {
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    font-weight: 500;
    margin-right: 22px;
    color: #14162e;
  }

  .user-item {
    margin-left: 10px;
    margin-right: 20px;
  }

  .user-status,
  .account-status {
    margin-right: 20px;
  }
}

.top-btn {
  margin: 30px 0px 30px 0px;
  font-size: 14px;
  color: #ffffff;

  &:nth-of-type(2) {
    margin-left: 20px;
  }

  &:nth-of-type(3) {
    margin-left: 20px;
  }

  &:nth-of-type(4) {
    margin-left: 20px;
  }
}

.right {
  margin-left: 1700px !important;
}

::v-deep .el-input__inner:focus {
  border-color: $mainColor;
}

.el-form-item__label-wrap .el-form-item__label {
  float: none;
}

.dialog-openboxsetting {
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin: 80px 80px;
}

.form-modify {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin: 10px 80px;

  .modify-right {
    margin-left: 80px;
  }

  ::v-deep .el-input__inner {
    // border-color: $mainColor;
    width: 300px;
  }
}

.addBox-dialog {
  ::v-deep .el-dialog__body {
    padding: 10px 80px;
  }

  ::v-deep .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
    font-size: 40px;
  }
}

.upload-btn {
  font-size: 14px;
  color: #ffffff;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.welfare_box {
  width: 740px;
  margin: 0 40px;
  box-sizing: border-box;

  .el-input {
    width: 300px;
    margin-right: 10px;
  }

  .el-select {
    width: 300px !important;
  }

  .welfare_list {
    width: 660px;
    // border: 1px solid red;
    transform: translateX(30px);

    .welfare_item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20px;

      span {
        font-size: 14px;
        font-weight: bold;
      }

      .el-input {
        width: 120px;
        margin: 0;
      }

      .el-select {
        width: 120px !important;
      }

      p {
        font-size: 14px;
        transform: translateX(-10px);
      }
    }
  }
}

.tag_tent {
  width: 90%;
  margin: 0 auto;
  .tag {
    margin: 0 10px;
  }
}

.set_box {
  width: 300px;
  margin: 0px 80px 40px;
  box-sizing: border-box;

  .Recharge_Data {
    width: 100%;
    height: 40px;
    margin-top: 10px;
    margin-bottom: 30px;
    display: flex;
    align-items: center;

    .Recharge_Data_box {
      width: 100%;
      height: 40px;
      margin: 0 auto;
      text-align: center;
      // display: flex;
      // align-items: center;
      // justify-content: space-between;

      .el-input {
        width: 150px;
        height: 35px;

        input {
          width: 150px;
          height: 35px;
        }
      }

      span {
        font-size: 14px;
        width: 100px;
      }
    }

    .operation {
      width: 12%;
      display: flex;
      justify-content: space-between;

      .el-icon {
        &-circle-plus,
        &-remove {
          font-size: 22px;
          color: #3b425d;
          margin-left: 10px;
        }
      }
    }
  }
}

.addBaby-dialog {
  ::v-deep .el-dialog__body {
    width: 678px;
    text-align: center;
  }

  .search-add {
    margin: 0 auto;
    padding: 50px 0px;
    height: 400px;
  }
}
</style>
